// 引入模块
const path = require('path');
const express = require('express');

// 创建并开启服务器
const app = express();
app.listen(3000, () => {
    console.log('服务器已开启');
})

// 接收post提交参数
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// 渲染登录页面
app.get('/login', (req, res) => {
    res.sendFile(path.join(__dirname, 'login.html'));
})

// 渲染注册页面
app.get('/register', (req, res) => {
    res.sendFile(path.join(__dirname, 'register.html'));
})

// 引入路由模块化
const myquery = require('./myquery');

// 登录
app.post('/login', async (req, res) => {
    let { username, password } = req.body;
    let [err, result] = await myquery(`select * from user where username = '${username}' and password = '${password}'`);
    if (err) {
        res.send({ code: 400, msg: err });
        return;
    }
    if (result.length == 0) {
        res.send({ code: 400, msg: '账号或密码错误' });
        return;
    }
    res.send({ code: 200, msg: '登录成功' });
})

// 注册
app.post('/register', async (req, res) => {
    let { username, password } = req.body;
    let [err1, result1] = await myquery(`select * from user where username = '${username}'`);
    if (err1) {
        res.send({ code: 400, msg: err1 });
        return;
    }
    if (result1.length != 0) {
        res.send({ code: 400, msg: '该用户已注册' });
        return;
    }

    let [err2, result2] = await myquery(`insert into user (username, password) values('${username}', '${password}')`);
    if (err2) {
        res.send({ code: 500, msg: err2 });
        return;
    }
    if (result2.insertId != 0) {
        res.send({ code: 200, msg: '注册成功' })
    }
    else {
        res.send({ code: 400, msg: '请稍后重试' })
    }
})
